package com.xiashitech.agent.instrumentation.base.context;

import org.jetbrains.annotations.Nullable;

import java.util.logging.Logger;

public enum ReentryContextStorage implements XSContextStorage {
    INSTANCE;

    private static final Logger logger = Logger.getLogger(ReentryContextStorage.class.getName());

    private static final ThreadLocal<XSContext> THREAD_LOCAL_STORAGE = new ThreadLocal();

    static XSContextStorage reentryStorage() {
        return ReentryContextStorage.INSTANCE;
    }

    @Override
    public void attach(XSContext toAttach) {
        if (toAttach == null) {
            return;
        }
        XSContext beforeAttach = current();
        if (toAttach == beforeAttach) {
            return;
        }
        THREAD_LOCAL_STORAGE.set(toAttach);
    }

    @Nullable
    @Override
    public XSContext current() {
        return THREAD_LOCAL_STORAGE.get();
    }

    @Override
    public void close() {
        THREAD_LOCAL_STORAGE.set(null);
    }
}
